package com.changgou.order.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * 描述
 *
 * @author ljh
 * @version 1.0
 * @package com.changgou.order.config *
 * @Date 2019-12-5
 * @since 1.0
 */
@Component
public class MyFeignInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        //核心:将头信息(包含了令牌的信息) 传递给下一个微服务
        //1.获取到当前线程的request请求对象
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes != null) {
            //2.添加一个头信息传递
            HttpServletRequest request = requestAttributes.getRequest();

            //获取所有的头名
            Enumeration<String> headerNames = request.getHeaderNames();
            //循环遍历 将头传递过去
            while (headerNames.hasMoreElements()) {
                String header = headerNames.nextElement();
                String value = request.getHeader(header);
                requestTemplate.header(header, value);//携带头递过去
            }
        }


    }
}
